from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from .serializers import AlgorithmSerializer, ImageSerializer
from .models import Algorithm, Image
from rest_framework.response import Response


# Create your views here.
class AlgorithmViewSet(ModelViewSet):
    serializer_class = AlgorithmSerializer
    queryset = Algorithm.objects.all()

    def list(self, request, *args, **kwargs):
        host = request.META['HTTP_HOST']
        res = super(AlgorithmViewSet, self).list(request, *args, **kwargs)
        for i in res.data:
            print(i)
            if i.get("img_url"):
                img_id = i.get("img_url")
                img_url = Image.objects.get(id=img_id).img_url.url
                i.update(img=host + img_url)
            else:
                i.update(img="")
        return res


class ImageViewSet(ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

    @action(methods=["POST"], detail=False)
    def upload_file(self, request):
        file = request.data.get("file")
        image = Image.objects.create(img_url=file)
        return Response(data={"img_id": image.id})
